// pages/giftCardBuy/giftCardBuy.js
const giftCardService = require('../../../api/giftCardService.js')
const utils = require('../../../utils/utils.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showCheckedImg: '',
    cardList: [],
    priceList: [],
    needPayValue: 0,
    cardInfo: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 获取从上一个页面传过来的活动id
    let giftCardActivityId = options.giftCardActivityId ? options.giftCardActivityId : null;
    // 如果活动id存在，查询该活动的详情
    if (giftCardActivityId) {
      giftCardService.queryActivityDetails(giftCardActivityId).then(res => {
        console.log(res)
        if (res.card) {
          let cardList = [];
          let priceList = [];
          if (res.card.cardStyles) {
            res.card.cardStyles.forEach((item, index) => {
              if (index === 0) {
                cardList.push({
                  ...item,
                  active: true
                })
              } else {
                cardList.push({
                  ...item,
                  active: false
                })
              }
            })
          }
          if (res.card.faces) {
            res.card.faces.forEach(item => {
              priceList.push({
                ...item,
                active: false
              })
            })
          }
          this.setData({
            cardInfo: res,
            cardList: cardList,
            priceList: priceList,
            showCheckedImg: res.card.cardStyles[0].imageUrl
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**
   * 点击礼品卡，切换对应的状态
   */
  clickChange: function(e) {
    console.log(e)
    var tempArr = this.data.cardList;
    tempArr.forEach(item => {
      if (item.styleId === e.currentTarget.dataset.styleid) {
        item.active = true;
        this.setData({
          showCheckedImg: item.imageUrl
        })
      } else {
        item.active = false;
      }
    })
    this.setData({
      cardList: tempArr
    })
  },
  /**
   * 价格点击事件，更新当前点击的价格显示状态
   */
  clickPrice: function(e) {
    let tempArr = this.data.priceList;
    let tempValue = 0;
    tempArr.forEach(item => {
      if (item.faceId === e.currentTarget.dataset.faceid) {
        item.active = !item.active;
        if (item.active) {
          tempValue = item.price;
        } else {
          tempValue = 0;
        }
      } else {
        item.active = false;
      }
    })
    this.setData({
      priceList: tempArr,
      needPayValue: tempValue
    })
  },

  // 跳转到使用须知
  toUseNeedKnow: function() {
    wx.setStorage({
      key: "_useNeedKnow",
      data: this.data.cardInfo
    })
    wx.navigateTo({
      url: '../useNeedKnow/useNeedKnow',
    })
  },

  /**
   * 购买按钮点击事件
   * 判断卡样式有没有选择，面额有没有选择
   */
  handleBuy: function() {
    let faceId = "";
    let payAmount = 0;
    let faceValue = 0;
    this.data.priceList.forEach(item => {
      if (item.active) {
        faceId = item.faceId;
        payAmount = item.price;
        faceValue = item.faceValue;
      }
    })
    if (!faceId) {
      wx.showToast({
        title: "请选择卡面额",
        icon: 'none',
        duration: 2000
      })
      return;
    }
    let styleId = '';
    let imageUrl = '';
    this.data.cardList.forEach(item => {
      if (item.active) {
        styleId = item.styleId;
        imageUrl = item.imageUrl;
      }
    })
    let postData = {
      cardId: this.data.cardInfo.card.id, // 礼品卡id
      cardName: this.data.cardInfo.name, // 礼品卡名称
      faceId: faceId, // 面额id
      giftCardActivityId: this.data.cardInfo.id, // 礼品卡活动id
      giftCardActivityName: this.data.cardInfo.name, // 礼品卡活动名称
      imageUrl: imageUrl, // 礼品卡图片
      payAmount: payAmount, // 总金额（具体卡支付金额）
      styleId: styleId, // 样式id
      total: faceValue // 总金额（具体卡面额）
    }
    giftCardService.createOrder(postData).then(res => {
      return res;
    }).then(orderId => {
      console.log(orderId)
      let postData = {
        orderId: orderId,
        payMethod: "WX_MINI_APP"
      }
      giftCardService.getPaySign(postData).then(res => {
        // console.log(res)
        var resData = JSON.parse(res);
        var sign = JSON.parse(resData.sign)
        // console.log(sign)
        wx.requestPayment({
          'timeStamp': sign.timeStamp,
          'nonceStr': sign.nonceStr,
          'package': sign.package ? sign.package : sign.packageValue,
          'signType': sign.signType,
          'paySign': sign.paySign,
          'success': function(res) {
            console.log('支付成功---------------')
            console.log(res)
            var selfTime = setInterval(function() {
              giftCardService.getStatusById(orderId).then(result => {
                console.log('查询交易结果-------------')
                console.log(result)
                if (result.status === 'SUCCESS' && result.cardNo) {
                  utils.setHideLoading(false);
                  clearInterval(selfTime)
                  wx.navigateTo({
                    url: '../cardBuyResult/cardBuyResult?cardNo=' + result.cardNo
                  })
                } else if (result.status === 'FAILED') {
                  utils.setHideLoading(false);
                  // 提示购卡失败原因
                  clearInterval(selfTime)
                  if (result.failedReason) {
                    wx.showToast({
                      title: result.failedReason,
                      icon: 'none',
                      duration: 2000
                    })
                  }
                } else {
                  utils.setHideLoading(true);
                }
              }).catch(err => {
                clearInterval(selfTime)
                wx.showToast({
                  title: res.errMsg,
                  icon: 'none',
                  duration: 2000
                })
              })
            }, 300)
          },
          'fail': function(res) {
            console.log('支付失败-------------')
            console.log(res)
            if (res.errMsg === 'requestPayment:fail cancel') {
              wx.showToast({
                title: '您取消了支付~',
                icon: 'none',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      }).catch(err => {
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  }
})